package com.ls.lserp.modules.trade.web;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.text.ParseException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.collections.map.HashedMap;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.support.RequestContext;

import com.ls.lserp.common.config.Global;
import com.ls.lserp.common.persistence.AjaxDone;
import com.ls.lserp.common.persistence.BaseEntity;
import com.ls.lserp.common.persistence.Page;
import com.ls.lserp.common.utils.ResourcesUtil;
import com.ls.lserp.common.utils.StringUtils;
import com.ls.lserp.common.utils.SystemPath;
import com.ls.lserp.common.utils.excel.template.ExcelTemplate;
import com.ls.lserp.common.web.BaseController;
import com.ls.lserp.dbaccess.Entity.FinanceEntity;
import com.ls.lserp.modules.order.entity.AuditInfo;
import com.ls.lserp.modules.order.entity.BigcargoOrder;
import com.ls.lserp.modules.sys.entity.Sequence;
import com.ls.lserp.modules.sys.utils.SequenceUtil;
import com.ls.lserp.modules.sys.utils.SystemMessageUtils;
import com.ls.lserp.modules.trade.entity.Enchase;
import com.ls.lserp.modules.trade.entity.Settlement;
import com.ls.lserp.modules.trade.service.SettlementService;
import freemarker.template.Configuration;
import groovy.util.ResourceException;

@Controller
@RequestMapping(value = "${adminPath}/settlement/single")
public class SettlementController extends BaseController{
	
	@Autowired
	// 保存 编辑 删除 方法
	private SettlementService settlementService;
	@Autowired
	Configuration freemarkerConfiguration;
	@ModelAttribute
	public FinanceEntity get(@RequestParam(required=false) String id) {
		
		// 判断id是否为空
		if (StringUtils.isNotBlank(id)){
			
			// 执行查询语句 查询基本信息
			return settlementService.get(Long.parseLong(id));
		}else{
			
			// 若为空，实例化
			return new FinanceEntity();
		}
	}
	
	
	/**
	 * @Title: 画面跳转用
	 * @return url
	 */
	@RequiresPermissions("settlement:single:view")
	@RequestMapping(value = { "" })
	public String list(Model model) {
		// 画面跳转
		return "modules/trade/settlement";
	}
	
	@RequiresPermissions("settlement:single:view")
	@RequestMapping(value = { "searchList" })
	public String searchList(FinanceEntity financeEntity, HttpServletRequest request, HttpServletResponse response,Model model) throws Exception{
		 	Map <Object, Object> listMap = new HashMap <Object, Object> ();
	        // ajax回调时使用的一览list名
	        request.setAttribute ("listNames", "finance");
	        // 拼接字符串供分页使用
 			StringBuilder searchParam = new StringBuilder();
 			//业务类别
 			searchParam.append("&financeCategory=");
 			searchParam.append(financeEntity.getFinanceCategory());
 			// 业务期间（年）
 			searchParam.append("&dateYear=");
 			searchParam.append(financeEntity.getDateYear());	
 			// 业务期间（月）
 			searchParam.append("&dateMonth=");
 			searchParam.append(financeEntity.getDateMonth());	
 			// tab状态
 			searchParam.append("&tabPageStatus=");
 			searchParam.append(financeEntity.getTabPageStatus());	
	        //放到Attribute里，使用Global类里面的SEARCH_PAEAM作为key
	        request.setAttribute (Global.SEARCH_PAEAM, searchParam);
	        // 查询一览页面数据
	        Page <FinanceEntity> page = settlementService.findList (new Page <FinanceEntity> (request, response),
	        		financeEntity);
	        // 读取文件生成字符串
	        String strUri = request.getContextPath () + Global.getAdminPath ();
	        String strHtml = "";
	        Map <String, Object> map = new HashedMap ();
	        map.put ("adminUri", strUri);
	        map.put ("financeList", page.getList ());
	        map.put ("pageNo", page.getPageNo ());
	        map.put ("pageSize", page.getPageSize ());
	        map.put("springMacroRequestContext", new RequestContext (request));
	        strHtml = FreeMarkerTemplateUtils
	                .processTemplateIntoString (freemarkerConfiguration.getTemplate ("exchangeForm.ftl"), map);
	        listMap.put ("finance", strHtml);
	        listMap.put ("page", page.getHtml ());
	        // ajax返回结果
	        return renderString (response, listMap);
	}
	
	/**
	 * 
	 * 功能：Java读取txt文件的内容 1：先获得文件句柄 2：获得文件句柄当做是输入一个字节码流，需要对这个输入流进行读取
	 * 3：读取到输入流后，需要读取生成字节流
	 * 
	 * @param filePath
	 * @return html
	 */
	public String readTxtFile(String filePath) {
		String strHtml = "";
		try {
			String encoding = "UTF-8";
			File file = new File(filePath);
			// 判断文件是否存在
			if (file.isFile()) {
				InputStreamReader read = new InputStreamReader(
						// 考虑到编码格式
						new FileInputStream(file), encoding);
				BufferedReader bufferedReader = new BufferedReader(read);
				String lingText = null;
				while ((lingText = bufferedReader.readLine()) != null) {
					strHtml += lingText;
				}
				read.close();
			} else {

			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return strHtml;
	}
	
	@RequiresPermissions("settlement:single:view")
	@RequestMapping(value = { "searchUnrecordedList" })
	public String searchUnrecordedList(FinanceEntity financeEntity, HttpServletRequest request, HttpServletResponse response,Model model) throws Exception{
		 	Map <Object, Object> listMap = new HashMap <Object, Object> ();
	        // ajax回调时使用的一览list名
	        request.setAttribute ("listNames", "finance");
	        // 拼接字符串供分页使用
 			StringBuilder searchParam = new StringBuilder();
 			//业务类别
 			searchParam.append("&financeCategory=");
 			searchParam.append(financeEntity.getFinanceCategory());
 			// 业务期间（年）
 			searchParam.append("&dateYear=");
 			searchParam.append(financeEntity.getDateYear());	
 			// 业务期间（月）
 			searchParam.append("&dateMonth=");
 			searchParam.append(financeEntity.getDateMonth());	
	        //放到Attribute里，使用Global类里面的SEARCH_PAEAM作为key
	        request.setAttribute (Global.SEARCH_PAEAM, searchParam);
	        // 查询一览页面数据
	        Page <FinanceEntity> page = settlementService.findUnrecordedList (new Page <FinanceEntity> (request, response),
	        		financeEntity);
	        // 读取文件生成字符串
	        String strUri = request.getContextPath () + Global.getAdminPath ();
	        String strHtml = "";
	        Map <String, Object> map = new HashedMap ();
	        map.put ("adminUri", strUri);
	        map.put ("financeList", page.getList ());
	        map.put ("pageNo", page.getPageNo ());
	        map.put ("pageSize", page.getPageSize ());
	        map.put("springMacroRequestContext", new RequestContext (request));
	        strHtml = FreeMarkerTemplateUtils
	                .processTemplateIntoString (freemarkerConfiguration.getTemplate ("selectFinance.ftl"), map);
	        listMap.put ("finance", strHtml);
	        listMap.put ("page", page.getHtml ());
	        // ajax返回结果
	        return renderString (response, listMap);
	}
	
	
	/**
	 * 创建结汇单信息窗口
	 * 
	 * @return
	 */
	@RequiresPermissions("settlement:single:view")
	@RequestMapping(value = {"form"})
	public String form(FinanceEntity financeEntity, HttpServletRequest request, HttpServletResponse response,
			Model model){
		try {
			
			financeEntity.setFinanceContractNo(SequenceUtil.financeCode().getReturnCode());
			model.addAttribute("ognizationList",settlementService.findOgnizationList());
		} catch (ParseException e) {
			logger.error(e.getMessage(),e);
		}
		model.addAttribute("financeEntity",financeEntity);
		//返回页面地址
		return "modules/trade/settlementCreate";
	}
	
	/**
	 * 查看画面
	 * 
	 * @return
	 */
	@RequiresPermissions("settlement:single:view")
	@RequestMapping(value = {"show"})
	public String show(FinanceEntity financeEntity, HttpServletRequest request, HttpServletResponse response,
			Model model){
		model.addAttribute("ognizationList",settlementService.findOgnizationList());
		model.addAttribute("financeEntity",settlementService.get(financeEntity));
		//返回页面地址
		return "modules/trade/settlementCreate";
	}
	
	
	/**
	    * 保存信息
	    * @param bookingOrders
	    * @param request
	    * @param model
	    * @param response
	    * @return
	    * @throws ResourceException 
	    */
	   @RequiresPermissions("settlement:single:edit")
	   @RequestMapping(value = "save")
	   @ResponseBody
	   public String save(FinanceEntity financeEntity, HttpServletRequest request, Model model, HttpServletResponse response ) throws ResourceException {
			try {
				// 保存基准数据及子项数据
				settlementService.saveFinance(financeEntity);
				/*//保存成功给指定人员发送邮件
				String url = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
				+ request.getContextPath() + Global.getAdminPath() + "/settlement/single/";
				SendEmailMessage sendEmailMessage = new SendEmailMessage();
				sendEmailMessage.setDataTheme(ResourcesUtil.getConfig("erp_send_mail_theme07"));
				sendEmailMessage.setDataMessage(ResourcesUtil.getConfig("erp_send_mail_textMessage07"));
				sendEmailMessage.setDataXXX01(UserUtils.getUser().getFirstName()+UserUtils.getUser().getLastName());
				sendEmailMessage.setDataXURLX(url);
				sendEmailMessage.setDataYYMMDD01(DateUtils.formatDate(settlement.getCreateDate(), "yyyy-MM-dd").toString());
				//发送邮件
				UserUtils.sendEmail(sendEmailMessage);*/
				// 保存成功返回提示信息
				return renderString(response,getText("settlement_save_success"));
			} catch (Exception e) {
				logger.error(e.getMessage(),e);
				return renderString(response,getText("settlement_save_fail"));
			}

	   }
	
	@RequiresPermissions("settlement:single:edit")
	@ResponseBody
	@RequestMapping(value = "exportInvoice")
	public String exportInvoice(FinanceEntity financeEntity ,HttpServletResponse response){
		try {
            // 模版
            String basePath = SystemPath.getClassPath();
            String tempFilePath = "/" + basePath + "proforma_invoice.xlsx";
            ExcelTemplate handle = this.settlementService.exportProformaInvoice(settlementService.get(financeEntity.getFinanceId()), tempFilePath);
            response.setContentType("application/octet-stream; charset=utf-8");
            response.setCharacterEncoding("UTF-8");
            response.setHeader("Content-disposition", "attachment; filename=" + financeEntity.getFinanceContractNo() + "_Invoice.xlsx");
            OutputStream os = response.getOutputStream();
            // 写到输出流并关闭资源
            handle.writeAndClose(tempFilePath, os);
            os.flush();
            os.close();
            handle.readClose(tempFilePath);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return null;
	}
	   
	/**
	 * 交货日期回调合同信息
	 * 
	 * @return
	 *//*
	@RequiresPermissions("settlement:single:view")
	@RequestMapping(value = {"findContractInfo"})
	public String findContractInfo(Settlement settlement, HttpServletRequest request, HttpServletResponse response,
			Model model){
		settlement = settlementService.findContractInfo(settlement);
		model.addAttribute("settlement",settlement);
		//返回页面地址
		return "modules/trade/settlementCreate";
	}*/
	
	/**
	 * 确认结汇单信息窗口
	 * 
	 * @return
	 */
	@RequiresPermissions("settlement:single:view")
	@RequestMapping(value = {"confirm"})
	public String confirm(Settlement settlement, HttpServletRequest request, HttpServletResponse response,
			Model model){
		
		model.addAttribute("settlement",settlement);
		//返回页面地址
		return "modules/trade/settlementConfirm";
	}
	
	/**
	 * 审核页面
	 * @param handBook
	 * @param model
	 * @return
	 */
	@RequiresPermissions("settlement:single:audit")
	@RequestMapping(value = "audit")
	public String audit(FinanceEntity financeEntity, Model model) {
		
		// 履历一览取得
		AuditInfo auditInfo = new AuditInfo();
		// ID
		auditInfo.setAuditRelateId(financeEntity.getId());
		// 阶段
		auditInfo.setAuditPhaseCd(ResourcesUtil.getConfig("audit_phase_finance"));
		AuditInfo resultInfo = settlementService.findAuditInfo(auditInfo);
		
		// 待审核状态可以审核
		if(resultInfo.getAuditStatus()==0){
			String strWaitAccept = ResourcesUtil.getConfig("reserver_meterial_wait_accept");
			if(!financeEntity.getAuditStatus().equals(strWaitAccept)){
				resultInfo.setAuditStatus(1L);
			}
		}
		
		// ID
		resultInfo.setAuditRelateId(financeEntity.getId());
		// 编号
		resultInfo.setAuditRelateNo(financeEntity.getFinanceContractNo());
		// 阶段
		resultInfo.setAuditPhaseCd(ResourcesUtil.getConfig("audit_phase_finance"));
		// 状态
		resultInfo.setVersion(financeEntity.getVersion());
		
		// 将实体类值赋给mvc model层返回jsp页面
		model.addAttribute("auditInfo", resultInfo);
		
		// 返回页面地址
		return "modules/order/auditInfo";
	}

	/**
     * 保存履历信息
     *
     * @param auditInfo
     * @param request
     * @param model
     * @param response
     * @return
     * @throws ResourceException
     */
    @RequiresPermissions("bigcargo:order:edit")
    @RequestMapping(value = "saveAudit")
    @ResponseBody
    public String saveAudit(AuditInfo auditInfo, HttpServletRequest request, Model model, HttpServletResponse response, HttpSession session) throws ResourceException {
        // 是否需要更新样品需求状态
        boolean isUpdateStatus = false;
        // 判断数据是否删除
        FinanceEntity financeEntity = get (Long.toString (auditInfo.getAuditRelateId ()));
        // 判断数据是否删除
        if (financeEntity.getFinanceContractNo() == null || BaseEntity.DEL_FLAG_DELETE.equals (financeEntity.getDeleteFlag ())) {
            // 返回提示信息
            return renderString (response, AjaxDone.error (getText ("This_record_has_been_deleted_or_modified_the_operation_failed")));
        }
        // 审核结果已经通过,返回错误提示信息
        AuditInfo pAuditResult = new AuditInfo ();
        pAuditResult.setAuditPhaseCd (auditInfo.getAuditPhaseCd ());
        pAuditResult.setAuditRelateId (auditInfo.getAuditRelateId ());
        if (settlementService.getAuditResult (pAuditResult) > 0) {
            // 返回提示信息
            return renderString (response, AjaxDone.error (getText ("This_record_has_been_deleted_or_modified_the_operation_failed")));
        }
        // 保存样品数据
        settlementService.saveAuditInfo (auditInfo, isUpdateStatus);
        // 保存成功返回提示信息
        return renderString (response, AjaxDone.ok (SystemMessageUtils.getMessageName ("audit_ok_msg")));
    }
}
